package com.study.tool;

import java.util.Random;

public class StringTool {

    private StringTool(){}

    /**
     * 获取low-->range(包括range)范围内的随机数
     * @param low
     * @param range
     * @return
     */
    public static int getRandomInRange(int low,int range)
    {
        int key = -999999999;
        Random random = new Random();
        while(key < low)
        {
            key = random.nextInt(range);
        }
        return key;
    }

    /**
     * 获取指定长度的随机数
     * @param length 长度
     * @return
     */
    public static String getDesignedLengthRandom(int length)
    {
        return String.valueOf(Math.random()).substring(2,length+2);
    }

    /**
     * 获取subStr第n次出现在str的的位置(index)：
     * @param str
     * @param subStr
     * @param showTime 出现的位置
     * @return
     */
    public static int getPositionByShowTime(String str,String subStr,int showTime)
    {
        if(str.length() < subStr.length())  //如果subStr长度大于str,或n超出总的出现次数,
        {
            return -1 ;						//返回没有
        }
        int count = 0;
        int offset = 0;
        int lastIndex = str.lastIndexOf(subStr);
        if(str.indexOf(subStr)!=-1)
        {
            do {
                offset = str.indexOf(subStr, offset);
                count++;
                if(showTime == count) {
                    break;
                }
                offset += subStr.length();
            }while (offset <= lastIndex);	//如果没有到母字符串末尾,则继续循环
        }
        return offset;
    }

    /**
     * 用replacement替换or删除str中第N个subStr
     * @param str
     * @param subStr
     * @param replacement
     * @param n
     * @return
     */
    public static String replaceSubstrByIndex(String str,String subStr,String replacement,int n)
    {
        int t = getPositionByShowTime(str, subStr, n);
        StringBuilder buffer = new StringBuilder();
        String s = str.substring(0,t);
        String sss = str.substring(t+subStr.length());
        buffer.append(s).append(replacement).append(sss);
        return buffer.toString();
    }

    public static boolean getFristStrcompare(String str,String substr){
        if(str == null ||substr == null){
            return false;
        }
        return str.substring(0,1).equals(substr);
    }


    public static void main(String[] args) {
         String s1 = "my";
         String s2 = "mydrmyeammymy";
         System.out.println("--> "+ StringTool.replaceSubstrByIndex(s2,s1,"",1));
        System.out.println(getFristStrcompare("C21000001061010000000067","C"));
    }
}
